<template>
  <div>
    <el-form
      :inline="true"
      :model="formInline"
      class="demo-form-inline"
      @submit.native.prevent
    >
      <el-form-item label="目标名称">
        <el-input
          v-model="formInline.objectName"
          @keyup.enter.native="findByQuery"
        ></el-input>
      </el-form-item>
      <el-form-item label="审核人">
        <el-input
          v-model="formInline.reviewer"
          @keyup.enter.native="findByQuery"
        ></el-input>
      </el-form-item>
      <el-form-item label="审核状态">
        <el-select v-model="formInline.review" clearable>
          <el-option label="未审核" value="0"> </el-option>
          <el-option label="通过" value="1"> </el-option>
          <el-option label="未通过" value="2"> </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="完成状态">
        <el-select v-model="formInline.status" clearable>
          <el-option label="未开始" value="0"> </el-option>
          <el-option label="进行中" value="1"> </el-option>
          <el-option label="已超时" value="2"> </el-option>
          <el-option label="已完成" value="3"> </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" round @click="findByQuery">查询</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="info" round @click="resetForm()">重置</el-button>
      </el-form-item>
      <el-form-item>
        <el-button
          type="success"
          round
          @click="addHandle()"
          v-if="level <= type"
          >新增</el-button
        >
      </el-form-item>
    </el-form>
    <el-table
      id="table"
      :data="listObject"
      style="width: 100%"
      :max-height="tableHeight"
      @expand-change="getKeyResults"
    >
      <el-table-column label="目标" prop="name"></el-table-column>
      <el-table-column type="expand" label="关键结果">
        <template slot-scope="props">
          <div style="width: 95%; margin: 0 auto">
            <el-button
              @click="addKeyResultsHandle(props.row.id)"
              size="mini"
              type="primary"
              v-if="props.row.review != 1"
              >增加关键结果</el-button
            >
            <el-table
              :data="props.row.keyResults"
              v-loading="!props.row.hasKeyResults"
            >
              <el-table-column label="关键结果" prop="name"></el-table-column>
              <el-table-column
                label="描述"
                prop="descriptors"
              ></el-table-column>
              <el-table-column label="完成状态" prop="status">
                <template slot-scope="scope">
                  <el-tag v-if="!scope.row.status" size="small" type=""
                    >未完成</el-tag
                  >
                  <el-tag v-if="scope.row.status" size="small" type="success"
                    >已完成</el-tag
                  >
                </template>
              </el-table-column>
              <el-table-column
                label="完成时间"
                prop="completeTime"
              ></el-table-column>
              <el-table-column label="操作">
                <template slot-scope="scope">
                  <el-switch
                    style="display: block"
                    v-model="scope.row.status"
                    active-color="#13ce66"
                    inactive-color="#ff4949"
                    active-text="已完成"
                    inactive-text="未完成"
                    @change="changeStauts(scope.row)"
                    :disabled="change || props.row.status == 3"
                    v-if="props.row.review == 1"
                  >
                  </el-switch>
                  <div v-if="props.row.review != 1">
                    <el-button
                      type="text"
                      @click="editKeyResultsHandle(scope.row.id)"
                      >编辑</el-button
                    >
                    <el-divider direction="vertical"></el-divider>
                    <el-popconfirm
                      title="确定要删除这条关键结果吗？"
                      @confirm="delKRHandle(scope.row.id)"
                    >
                      <el-button type="text" slot="reference">删除</el-button>
                    </el-popconfirm>
                  </div>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </template>
      </el-table-column>
      <el-table-column
        label="上级目标"
        prop="parentName"
        v-if="type != 1"
      ></el-table-column>
      <el-table-column label="描述" prop="descriptors"></el-table-column>
      <el-table-column label="审核人" prop="reviewer"></el-table-column>
      <el-table-column label="审核状态" prop="review">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.review === 0" size="small" type=""
            >未审核</el-tag
          >
          <el-tag v-if="scope.row.review === 1" size="small" type="success"
            >通过</el-tag
          >
          <el-tag v-if="scope.row.review === 2" size="small" type="danger"
            >未通过</el-tag
          >
        </template>
      </el-table-column>
      <el-table-column label="状态" prop="status">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.status === 0" size="small" type="info"
            >未开始</el-tag
          >
          <el-tag v-if="scope.row.status === 1" size="small" type=""
            >进行中</el-tag
          >
          <el-tag v-if="scope.row.status === 2" size="small" type="danger"
            >已超时</el-tag
          >
          <el-tag v-if="scope.row.status === 3" size="small" type="success"
            >已完成</el-tag
          >
        </template></el-table-column
      >
      <el-table-column label="难度星级" prop="stars" width="200px">
        <template slot-scope="scope">
          <el-rate
            v-model="scope.row.stars"
            disabled
            :texts="texts"
            show-text
            text-color="#ff9900"
          >
          </el-rate>
        </template>
      </el-table-column>
      <el-table-column label="得分" prop="score">
        <template slot-scope="scope">
          <p v-if="scope.row.score >= 0.6" style="color: yellowgreen">
            {{ scope.row.score }}
          </p>
          <p v-if="scope.row.score < 0.6" style="color: red">
            {{ scope.row.score }}
          </p>
        </template>
      </el-table-column>
      <el-table-column label="截止时间" prop="endTime"></el-table-column>
      <el-table-column label="未通过原因" prop="reason"></el-table-column>
      <el-table-column label="操作" width="120">
        <template slot-scope="scope">
          <el-button
            type="text"
            @click="editObjectiveHandle(scope.row.id)"
            :disabled="scope.row.review == 1"
            >编辑</el-button
          >
          <el-divider direction="vertical"></el-divider>
          <el-popconfirm
            title="确定要删除这条目标及关键结果吗？"
            @confirm="delOKRHandle(scope.row.id)"
          >
            <el-button
              type="text"
              slot="reference"
              :disabled="scope.row.review == 1"
              >删除</el-button
            >
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      layout="total, sizes, prev, pager, next, jumper"
      :current-page="current"
      :page-sizes="[10, 15, 20, 50]"
      :page-size="size"
      :total="total"
    >
    </el-pagination>
    <!-- 新增OKR -->
    <el-dialog
      title="新增OKR"
      :visible.sync="dialogFormVisible"
      width="600px"
      :before-close="closeHandle"
    >
      <el-form
        :model="editForm"
        :rules="rules"
        ref="editForm"
        label-position="left"
        label-width="100px"
        class="demo-editForm"
      >
        <strong class="font-size">目标:</strong>
        <el-form-item label="名称" prop="name">
          <el-input v-model="editForm.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="上级目标" prop="parentId" v-if="type != 1">
          <el-select v-model="editForm.parentId" placeholder="请选择上级目标">
            <el-option
              v-for="parentObject in parentObjectList"
              :label="parentObject.name"
              :value="parentObject.id"
              :key="parentObject.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          label="选择部门"
          prop="departmentId"
          v-if="type == 2 && level == 1"
        >
          <el-select v-model="editForm.departmentId" placeholder="请选择部门">
            <el-option
              v-for="department in departmentList"
              :label="department.name"
              :value="department.id"
              :key="department.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="描述" prop="descriptors">
          <el-input
            type="textarea"
            :rows="4"
            v-model="editForm.descriptors"
          ></el-input>
        </el-form-item>
        <el-form-item label="截止时间" prop="endTime">
          <el-date-picker
            v-model="editForm.endTime"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
          >
          </el-date-picker>
        </el-form-item>
        <strong class="font-size">关键结果:</strong>
        <div
          v-for="(keyResults, index) in editForm.keyResultsList"
          :key="index"
        >
          <el-form-item
            label="名称"
            :prop="'keyResultsList.' + index + '.name'"
            :rules="rules.name"
          >
            <el-input v-model="keyResults.name"></el-input>
          </el-form-item>
          <el-form-item
            label="描述"
            :prop="'keyResultsList.' + index + '.descriptors'"
            :rules="rules.descriptors"
          >
            <el-input
              type="textarea"
              :rows="4"
              v-model="keyResults.descriptors"
            ></el-input>
          </el-form-item>
          <el-form-item>
            <i class="el-icon-delete" @click="deleteItem(item, index)"></i>
          </el-form-item>
        </div>
        <el-form-item
          ><el-button @click="addItem" size="mini" type="primary"
            >增加关键结果</el-button
          ></el-form-item
        >
        <el-form-item label="审核人" prop="reviewUid">
          <el-select v-model="editForm.reviewUid" placeholder="请选择审核人">
            <el-option
              v-for="reviewer in reviewerList"
              :key="reviewer.id"
              :label="reviewer.name"
              :value="reviewer.id"
            >
              <span style="float: left">{{ reviewer.name }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{
                reviewer.positionName
              }}</span>
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeHandle">取 消</el-button>
        <el-button type="primary" @click="submitEditForm('editForm')"
          >确 定</el-button
        >
      </div>
    </el-dialog>
    <el-dialog
      title="编辑目标"
      :visible.sync="dialogObjectiveFormVisible"
      width="600px"
      :before-close="closeObjectiveHandle"
    >
      <el-form
        :model="editObjectiveForm"
        :rules="rules"
        ref="editObjectiveForm"
        label-position="left"
        label-width="100px"
        class="demo-editForm"
      >
        <el-form-item label="名称" prop="name">
          <el-input
            v-model="editObjectiveForm.name"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="上级目标" prop="parentId" v-if="type != 1">
          <el-select
            v-model="editObjectiveForm.parentId"
            placeholder="请选择上级目标"
          >
            <el-option
              v-for="parentObject in parentObjectList"
              :label="parentObject.name"
              :value="parentObject.id"
              :key="parentObject.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          label="选择部门"
          prop="departmentId"
          v-if="type == 2 && level == 1"
        >
          <el-select
            v-model="editObjectiveForm.departmentId"
            placeholder="请选择部门"
          >
            <el-option
              v-for="department in departmentList"
              :label="department.name"
              :value="department.id"
              :key="department.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="描述" prop="descriptors">
          <el-input
            type="textarea"
            :rows="4"
            v-model="editObjectiveForm.descriptors"
          ></el-input>
        </el-form-item>
        <el-form-item label="截止时间" prop="endTime">
          <el-date-picker
            v-model="editObjectiveForm.endTime"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="审核人" prop="reviewUid">
          <el-select
            v-model="editObjectiveForm.reviewUid"
            placeholder="请选择审核人"
          >
            <el-option
              v-for="reviewer in reviewerList"
              :label="reviewer.name"
              :value="reviewer.id"
              :key="reviewer.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeObjectiveHandle">取 消</el-button>
        <el-button
          type="primary"
          @click="submitObjectiveEditForm('editObjectiveForm')"
          >确 定</el-button
        >
      </div>
    </el-dialog>
    <el-dialog
      :title="keyResultsTitle"
      :visible.sync="dialogKeyResultsFormVisible"
      width="600px"
      :before-close="closeKeyResultsHandle"
    >
      <el-form
        :model="editKeyResultsForm"
        :rules="rules"
        ref="editKeyResultsForm"
        label-position="left"
        label-width="100px"
        class="demo-editForm"
      >
        <el-form-item label="名称" prop="name">
          <el-input
            v-model="editKeyResultsForm.name"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="描述" prop="descriptors">
          <el-input
            type="textarea"
            :rows="4"
            v-model="editKeyResultsForm.descriptors"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeKeyResultsHandle">取 消</el-button>
        <el-button
          type="primary"
          @click="submitKeyResultsEditForm('editKeyResultsForm')"
          >确 定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>
<script>
export default {
  name: "CreatedByMe",
  props: {
    type: {
      type: Number,
      default: -1,
    },
  },
  computed: {
    level: {
      get() {
        return this.$store.state.userInfo.info.positionLevel;
      },
    },
  },
  data() {
    return {
      tableHeight: 500,
      texts: ["简单", "一般", "有点难", "值得挑战", "极具挑战"],
      dialogFormVisible: false,
      dialogObjectiveFormVisible: false,
      dialogKeyResultsFormVisible: false,
      listObject: [],
      listKeyResults: [],
      departmentList: [],
      current: 1,
      size: 10,
      total: 0,
      editForm: {
        keyResultsList: [],
      },
      editObjectiveForm: {},
      editKeyResultsForm: {},
      keyResultsTitle: "",
      change: false,
      formInline: {},
      parentObjectList: [],
      reviewerList: [],
      rules: {
        name: [
          {
            required: true,
            message: "目标名称不能为空！",
            trigger: ["change", "blur"],
          },
        ],
        parentId: [
          {
            required: true,
            message: "上级目标不能为空！",
            trigger: ["change", "blur"],
          },
        ],
        descriptors: [
          {
            required: true,
            message: "描述不能为空！",
            trigger: ["change", "blur"],
          },
        ],
        endTime: [
          {
            required: true,
            message: "截止时间不能为空！",
            trigger: ["change", "blur"],
          },
        ],
        reviewUid: [
          {
            required: true,
            message: "审核人不能为空！",
            trigger: ["change", "blur"],
          },
        ],
        departmentId: [
          {
            required: true,
            message: "部门不能为空！",
            trigger: ["change", "blur"],
          },
        ],
      },
    };
  },
  methods: {
    addItem() {
      this.editForm.keyResultsList.push({ name: "", descriptors: "" });
    },
    deleteItem(index) {
      this.editForm.keyResultsList.splice(index, 1);
    },
    handleSizeChange(val) {
      this.size = val;
      // // this.getUserList();
    },
    handleCurrentChange(val) {
      this.current = val;
      // this.getUserList();
    },
    findByQuery() {
      this.current = 1;
      this.getListObject();
    },
    getListObject() {
      this.$axios
        .post("/objective/page", {
          objectName: this.formInline.objectName,
          createUid: 1,
          reviewer: this.formInline.reviewer,
          status: this.formInline.status,
          review: this.formInline.review,
          current: this.current,
          size: this.size,
          type: this.type,
        })
        .then((res) => {
          this.listObject = res.data.data.records;
        });
    },
    delOKRHandle(id) {
      this.$axios.delete("/objective/del/" + id).then((res) => {
        this.$message({
          showClose: true,
          type: "success",
          message: res.data.message,
          onClose: () => {
            this.getListObject();
          },
        });
      });
    },
    delKRHandle(id) {
      this.$axios.delete("/key-results/del/" + id).then((res) => {
        this.$message({
          showClose: true,
          type: "success",
          message: res.data.message,
          onClose: () => {
            this.getListObject();
          },
        });
      });
    },
    changeStauts(row) {
      (this.change = true),
        this.$axios.post("/key-results/changeStatus", row).then((res) => {
          this.$message({
            showClose: true,
            type: "success",
            message: res.data.message,
            onClose: () => {
              this.getListObject();
              this.change = false;
            },
          });
        });
    },
    addHandle() {
      var that = this;
      this.getReviewer().then(function () {
        if (that.type != 1) {
          var thatt = that;
          that.getParentObjective().then(function () {
            if (thatt.type == 2) {
              if (thatt.level == 1) {
                thatt.getDepartmentList();
              } else {
                thatt.editForm.departmentId =
                  thatt.$store.state.userInfo.info.departmentId;
              }
            }
          });
        }
      });
      this.dialogFormVisible = true;
    },
    editObjectiveHandle(id) {
      this.$axios.get("/objective/info/" + id).then((res) => {
        this.editObjectiveForm = res.data.data;
        var that = this;
        this.getReviewer().then(function () {
          if (that.type != 1) {
            var thatt = that;
            that.getParentObjective().then(function () {
              if (thatt.type == 2) {
                if (thatt.level == 1) {
                  thatt.getDepartmentList();
                } else {
                  thatt.editForm.departmentId =
                    thatt.$store.state.userInfo.info.departmentId;
                }
              }
            });
          }
        });
      });
      this.dialogObjectiveFormVisible = true;
    },
    editKeyResultsHandle(id) {
      this.keyResultsTitle = "编辑关键结果";
      this.$axios.get("/key-results/info/" + id).then((res) => {
        this.editKeyResultsForm = res.data.data;
      });
      this.dialogKeyResultsFormVisible = true;
    },
    addKeyResultsHandle(id) {
      this.keyResultsTitle = "新增关键结果";
      this.editKeyResultsForm.objectiveId = id;
      this.dialogKeyResultsFormVisible = true;
    },
    async getDepartmentList() {
      await this.$axios.get("/department/list").then((res) => {
        this.departmentList = res.data.data;
      });
    },
    async getParentObjective() {
      await this.$axios
        .get("/objective/parentObjective/" + this.type)
        .then((res) => {
          this.parentObjectList = res.data.data;
        });
    },
    async getReviewer() {
      await this.$axios.get("/objective/reviewer/" + this.type).then((res) => {
        this.reviewerList = res.data.data;
      });
    },
    closeHandle() {
      this.editForm = { keyResultsList: [] };
      this.$refs["editForm"].resetFields();
      this.dialogFormVisible = false;
    },
    closeObjectiveHandle() {
      this.$refs["editObjectiveForm"].resetFields();
      this.dialogObjectiveFormVisible = false;
    },
    closeKeyResultsHandle() {
      this.editKeyResultsForm = {};
      this.$refs["editKeyResultsForm"].resetFields();
      this.dialogKeyResultsFormVisible = false;
    },
    submitEditForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.$axios
            .post("/objective/add/" + this.type, this.editForm)
            .then((res) => {
              this.closeHandle();
              this.$message({
                showClose: true,
                message: res.data.message,
                type: "success",
                onClose: () => {
                  this.getListObject();
                },
              });
            });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    submitObjectiveEditForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.$axios
            .post("/objective/update", this.editObjectiveForm)
            .then((res) => {
              this.closeObjectiveHandle();
              this.$message({
                showClose: true,
                message: res.data.message,
                type: "success",
                onClose: () => {
                  this.getListObject();
                },
              });
            });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    submitKeyResultsEditForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.$axios
            .post("/key-results/save", this.editKeyResultsForm)
            .then((res) => {
              this.closeKeyResultsHandle();
              this.$message({
                showClose: true,
                message: res.data.message,
                type: "success",
                onClose: () => {
                  this.getListObject();
                },
              });
            });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    // 展开事件----动态获取内嵌表数据
    getKeyResults(row) {
      // console.log(row)
      if (!row.hasKeyResults) {
        //根据hasKeyResults判定是否已经加载了数据
        this.$axios.get("/key-results/list/" + row.id).then((res) => {
          row.keyResults = res.data.data;
          row.hasKeyResults = true; //加载成功之后更新标识
        });
      }
    },
    resetForm() {
      this.formInline = {};
    },
  },
};
</script>
<style scoped>
.font-size {
  font-size: large;
}
</style>